package com.idea.relax.tool.wechat.config;

import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.StringUtils;

import java.lang.annotation.*;
import java.util.Map;
import java.util.Objects;

/**
 * @author: 沉香
 * @date: 2023/1/30
 * @description:
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ConditionalOnNotEmpty.ConditionalOnNotEmptyCondition.class)
@interface ConditionalOnNotEmpty {

    String[] values();

    class ConditionalOnNotEmptyCondition extends SpringBootCondition {

        @Override
        public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
            Environment environment = context.getEnvironment();
            Map<String, Object> attrMap = metadata.getAnnotationAttributes(ConditionalOnNotEmpty.class.getName());
            String[] values = (String[]) Objects.requireNonNull(attrMap).get("values");
            if (values.length == 0){
                throw new IllegalStateException("values is not null!");
            }
            for (int i = 0; i < values.length; i++) {
                String value = values[i];
                String property = environment.getProperty(value, "");
                if (!StringUtils.hasText(property)){
                    return ConditionOutcome.noMatch("");
                }
            }
            return ConditionOutcome.match();
        }
    }


}
